package de.ubschmidt.capi.util;

import java.io.UnsupportedEncodingException;

/**
 *
 */
public final class StringUtil {

    private static final String CHARSET = "ISO-8859-1";

    private StringUtil() {
    }

    /**
     * Retrieve a zero-terminated character sequence from the
     * specified byte array.
     *
     * <p>The byte array is decoded according to character set ISO-8859-1.
     *
     * @param buf
     * @return
     */
    public static String szString(final byte [] buf) {
        int length = buf.length;

        for (int i = 0; i < length; ++i) {
            if (buf[i] == 0) {
                length = i;
                break;
            }
        }

        try {
            return new String(buf, 0, length, CHARSET);
        } catch (UnsupportedEncodingException e) {
            // Unreachable in practice since the specified charset is
            // always supported.
            throw new RuntimeException("szString(): unknown charset "
                    + CHARSET);
        }
    }

    /**
     * Convert the specified array of bytes into a {@code String} using
     * the ISO-8859-1 encoding.
     *
     * @param buf The array of bytes.
     * @return The {@code String}.
     */
    public static String string(final byte [] buf) {
        try {
            return new java.lang.String(buf, CHARSET);
        } catch (UnsupportedEncodingException ex) {
            // Unreachable in practice since the specified charset is
            // always supported.
            throw new RuntimeException("szString(): unknown charset "
                    + CHARSET);
        }
    }

    /**
     * Convert the specified array of bytes into a {@code String} using
     * the ISO-8859-1 encoding.
     *
     * @param buf The array of bytes.
     * @param offset
     * @return The {@code String}.
     */
    public static String string(final byte [] buf, final int offset) {
        try {
            return new java.lang.String(buf, offset, buf.length - offset,
                    CHARSET);
        } catch (UnsupportedEncodingException ex) {
            // Unreachable in practice since the specified charset is
            // always supported.
            throw new RuntimeException("szString(): unknown charset "
                    + CHARSET);
        }
    }

    /**
     * Encode the specified string as an array of bytes according to ISO-8859-1.
     *
     * @param s The string.
     * @return The string encoded as an array of bytes according to ISO-8859-1.
     */
    public static byte [] byteBuf(final String s) {
        try {
            return s.getBytes(CHARSET);
        } catch (UnsupportedEncodingException e) {
            // Unreachable in practice since the specified charset is
            // always supported.
            throw new RuntimeException("byteBuf(): unknown charset " + CHARSET);
        }
    }

}
